/****************************************
 * 派乐科技馆EV3红外遥控模块
 * 模块：Pillar_IRremote
 * 连线：D10
 * 时间：2021.01.04
 ****************************************/

#include <Wire.h>
#include <IRremote.h>  // 使用IRRemote函数库

#define SLAVE_ADDRESS 0x05  // 红外通信模块IIC地址设置为0x05
const int irReceiverPin = 10;  // 定义irReceiverPin变量为PIN9接口
IRrecv irrecv(irReceiverPin); // 设置irReceiverPin定义的端口为红外信号接收端口
decode_results results;    // 定义results变量为红外结果存放位置

void setup() 
{
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
  delay(2000);
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
  irrecv.enableIRIn();   // 启动红外解码  
  digitalWrite(13, LOW);
}

int val;
int flag=0;

void loop()
{
  if(flag==1)
  {
    flag=0;
  }
  if (irrecv.decode(&results))  // 如果接收到红外信号
  {
    digitalWrite(13, HIGH);
    translateIR();  // 解码
    irrecv.resume();
    digitalWrite(13, LOW);
  }
}

void receiveData(int byteCount)
{
    while(Wire.available()>0) 
    {
      flag=1;
    }
}

void sendData()
{
  Wire.write(val);
}

void translateIR()
{
  switch(results.value)
  {
    case 0xFF9867:
      val = 0;
      break;
    case 0xFFA25D:
      val = 1;
      break;
    case 0xFF629D:
      val = 2;
      break;
    case 0xFFE21D:
      val = 3;
      break;
    case 0xFF22DD:
      val = 4;
      break;
    case 0xFF02FD:
      val = 5;
      break;
    case 0xFFC23D:
      val = 6;
      break;
    case 0xFFE01F:
      val = 7;
      break;
    case 0xFFA857:
      val = 8;
      break;
    case 0xFF906F:
      val = 9;
      break;
    case 0xFF18E7:
      val = 10;  // 上
      break;
    case 0xFF4AB5:
      val = 11;  // 下
      break;
    case 0xFF10EF:
      val = 12;  // 左
      break;
    case 0xFF5AA5:
      val = 13;  // 右
      break;
    case 0xFF38C7:
      val = 14;  // OK
      break;
    case 0xFF6897:
      val = 15;  // *
      break;
    case 0xFFB04F:
      val = 16;  // #
      break;
    default:
      break;
  }
}
